package org.neuedu.vblogserver.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.neuedu.vblogserver.bean.Category;
import org.neuedu.vblogserver.bean.RespBean;
import org.neuedu.vblogserver.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryService {
    @Autowired
    CategoryMapper categoryMapper;
    public PageInfo getCategory(String serchKeyWord,int pageNum, int pageSize) {
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = categoryMapper.getCategory(serchKeyWord);
        PageInfo pageInfo = new PageInfo(categories);
        return pageInfo;
    }

    public RespBean addCategory(Category category) {
        // 如果数据库不支持 时间函数 作为默认值，自行创建date
        // category.setCreateTime(new Date());
        if (category.getCateName() == null || category.getCateName().trim().equals("")) {
            return RespBean.error(500, "新增栏目名称不合法");
        }else{
            int i = categoryMapper.addCategory(category);
            if (i == 0) {
                return RespBean.error(500, "新增栏目失败");
            }else{
                return RespBean.success(200, "新增栏目成功");
            }
        }
    }

    public RespBean delCategory(int id) {
        int count = categoryMapper.serchReferArticle(id);
        if (count == 0) {
            int i = categoryMapper.delCategory(id);
            if (i == 0) {
                return RespBean.error(500, "删除栏目失败");
            }else{
                return RespBean.success(200, "删除栏目成功");
            }
        }else{
            return RespBean.error(500, "栏目下有文章信息，不能删除");
        }
    }

    public RespBean multiDelCategory(int[] ids) {
        for (int id : ids) {
            int count = categoryMapper.serchReferArticle(id);
            if (count != 0) {
                return RespBean.error(500, "编号【"+id+"】栏目下有文章信息，不能删除");
            }
        }
        int i = categoryMapper.multiDelCategory(ids);
        if (i == 0) {
            return RespBean.error(500, "批量删除栏目失败");
        }else{
            return RespBean.success(200, "批量删除栏目成功");
        }
    }

    public RespBean updateCategory(Category category) {
        if (category.getCateName() == null || category.getCateName().trim().equals("")) {
            return RespBean.error(500, "更新栏目名称不合法");
        }else{
            int i = categoryMapper.updateCategory(category);
            if (i == 0) {
                return RespBean.error(500, "更新栏目失败");
            }else{
                return RespBean.success(200, "更新栏目成功");
            }
        }
    }
}
